package com.ziyan.controller;

import com.ziyan.cache.CacheManager;
import com.ziyan.dto.RequestDTO;
import com.ziyan.error.ErrorCode;
import com.ziyan.error.UCException;
import com.ziyan.service.AppInfoService;
import com.ziyan.service.URLService;
import com.ziyan.utils.URLUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 *
 * Created by ZMy on 2017/5/24.
 */

@RestController
@RequestMapping("/api")
public class UrlChangeController {
    @Autowired
    private AppInfoService appInfoService;
    @Autowired
    private URLService urlService;

    @PostMapping("/uoc")
    public Map<String, String> toShortUrl(@RequestBody RequestDTO requestDTO) {
        if (requestDTO.isBlank()) {
            throw new UCException(ErrorCode.miss_param);
        }

        appInfoService.checkSign(requestDTO);
        if (!URLUtil.isUrl(requestDTO.getUrl())) {
            throw new UCException(ErrorCode.invalid_params);
        }

        String resultUrl = null;
        if (requestDTO.getAction() == RequestDTO.ACTION_TO_SHORT) {
            String appid = requestDTO.getAppid();
            if(CacheManager.isLimit(appid)){
                throw new UCException(ErrorCode.test_limit);
            }

            //TODO 长链接转短链接
            resultUrl = urlService.toShortUrl(requestDTO.getUrl());
        } else if (requestDTO.getAction() == RequestDTO.ACTION_TO_LONG) {
            //TODO 短链接转长链接
            resultUrl = urlService.toNomalUrl(requestDTO.getUrl());
        } else {
            throw new UCException(ErrorCode.miss_param);
        }
        Map<String, String> map = new HashMap<>();
        map.put("errorCode", "0");
        map.put("message", "success");
        map.put("resultUrl", resultUrl);

        return map;
    }
}
